// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ListUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.SupplierFlow;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.SupplierFlowMapper;
import com.fowo.api.model.supplier.flow.SupplierFlowExcelPo;
import com.fowo.api.model.supplier.flow.SupplierFlowImportPo;
import com.fowo.api.model.supplier.flow.SupplierFlowItemVo;
import com.fowo.api.model.supplier.flow.SupplierFlowSearchParamPo;
import com.fowo.api.model.supplier.flow.SupplierFlowVo;
import com.fowo.api.model.supplier.flow.node.SupplierFlowNodeSearchParamPo;
import com.fowo.api.service.SupplierFlowNodeService;
import com.fowo.api.service.SupplierFlowService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.component.SysDataActivityAopHelper;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.model.SysDictAllItem;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysDictService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 供应商流程 服务实现基类
 * @author 蜂窝蜜造平台 配置人：任凯
 */
@Slf4j
@DataObjectType(SupplierFlow.class)
@DS("ds24")
public class SupplierFlowBaseServiceImpl
  extends ServiceImpl<SupplierFlowMapper, SupplierFlow>
  implements SupplierFlowService {

  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>();
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected SupplierFlowService self;

  @Resource
  protected SupplierFlowNodeService supplierFlowNodeService;

  @Resource
  private SysDictService sysDictService;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Resource
  protected Validator validator;

  /**
   * 创建供应商流程
   * @param model 供应商流程
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(SupplierFlowVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    SupplierFlow entity = new SupplierFlow();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }

    if (model.getStatus() == null) {
      entity.setStatus("1");
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      return entity.getId();
    }
    throw new Exception("供应商流程保存失败");
  }

  /**
   * 更新所有子表
   * @param model 供应商流程
   */
  protected void updateAllChilds(SupplierFlowVo model) throws Exception {
    if (model.getNode() != null) {
      supplierFlowNodeService.saveAllBySupplierFlowNode(model, model.getNode());
    }
  }

  /**
   * 更新供应商流程
   * @param model 供应商流程
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(SupplierFlowVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    SupplierFlow entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("供应商流程不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "createTime",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      return true;
    }
    return false;
  }/**
   * 更新供应商流程（带空值）
   * @param model 供应商流程
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(SupplierFlowVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    SupplierFlow entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("供应商流程不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(SupplierFlow::getLastUpdateTime, model.getLastUpdateTime())
      .set(SupplierFlow::getLastUpdateUser, model.getLastUpdateUser())
      .set(SupplierFlow::getEnCode, model.getEnCode())
      .set(SupplierFlow::getStatus, model.getStatus())
      .set(SupplierFlow::getIdField, model.getIdField())
      .set(SupplierFlow::getCodeField, model.getCodeField())
      .set(SupplierFlow::getTitleField, model.getTitleField())
      .set(SupplierFlow::getStatusField, model.getStatusField())
      .set(SupplierFlow::getEndTimeField, model.getEndTimeField())
      .set(SupplierFlow::getRemark, model.getRemark())
      .eq(SupplierFlow::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(SupplierFlowSearchParamPo search) {
    return false;
  }

  /**
   * 删除供应商流程
   * @param id 供应商流程的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    return this.removeById(id);
  }

  /**
   * 批量删除供应商流程
   * @param ids 供应商流程的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<SupplierFlowImportPo> excelToImportRow(
    SupplierFlowImportPo row,
    Integer rowNumber,
    SupplierFlowVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<SupplierFlowImportPo> ir = new ImportRow<SupplierFlowImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<SupplierFlowImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new SupplierFlowVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, SupplierFlowImportPo.class);

    // 一般数据处理
    if (StringUtils.hasText(row.getEnCode())) {
      List<SysDictAllItem> enCodeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "enCode",
          n -> sysDictService.getDictItems("SCM00195")
        );
      SupplierFlowVo finalVo = vo;
      enCodeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getEnCode()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setEnCode(i.getItemValue()),
          () ->
            ir.addError(
              "enCode",
              String.format(
                "必须为 %s 中之一",
                enCodeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getStatus())) {
      List<SysDictAllItem> statusItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "status",
          n -> sysDictService.getDictItems("SCM00134")
        );
      SupplierFlowVo finalVo = vo;
      statusItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getStatus()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setStatus(i.getItemValue()),
          () ->
            ir.addError(
              "status",
              String.format(
                "必须为 %s 中之一",
                statusItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getIdField())) {
      List<SysDictAllItem> idFieldItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "idField",
          n -> sysDictService.getDictItems("SCM00200")
        );
      SupplierFlowVo finalVo = vo;
      List<String> idFieldTexts = Arrays
        .stream(row.getIdField().split(","))
        .filter(StringUtils::hasText)
        .collect(Collectors.toList());
      finalVo.setIdField(
        idFieldItems
          .stream()
          .filter(i -> idFieldTexts.contains(i.getItemText()))
          .map(SysDictAllItem::getItemValue)
          .collect(Collectors.joining(","))
      );
    }
    if (StringUtils.hasText(row.getTitleField())) {
      List<SysDictAllItem> titleFieldItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "titleField",
          n -> sysDictService.getDictItems("SCM00200")
        );
      SupplierFlowVo finalVo = vo;
      titleFieldItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getTitleField()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setTitleField(i.getItemValue()),
          () ->
            ir.addError(
              "titleField",
              String.format(
                "必须为 %s 中之一",
                titleFieldItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getStatusField())) {
      List<SysDictAllItem> statusFieldItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "statusField",
          n -> sysDictService.getDictItems("SCM00200")
        );
      SupplierFlowVo finalVo = vo;
      statusFieldItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getStatusField()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setStatusField(i.getItemValue()),
          () ->
            ir.addError(
              "statusField",
              String.format(
                "必须为 %s 中之一",
                statusFieldItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getEndTimeField())) {
      List<SysDictAllItem> endTimeFieldItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "endTimeField",
          n -> sysDictService.getDictItems("SCM00200")
        );
      SupplierFlowVo finalVo = vo;
      endTimeFieldItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getEndTimeField()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setEndTimeField(i.getItemValue()),
          () ->
            ir.addError(
              "endTimeField",
              String.format(
                "必须为 %s 中之一",
                endTimeFieldItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<SupplierFlowImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<SupplierFlowImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            SupplierFlowImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(
              SupplierFlowImportPo row,
              AnalysisContext cxt
            ) {
              SupplierFlowVo vo = new SupplierFlowVo();
              ImportRow<SupplierFlowImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @DataActivity(action = SysDataActivityAction.Import)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<SupplierFlowImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    SysDataActivityAopHelper.clear();
    final SysDataActivityAopHelper.DataActivityAopContext context =
      SysDataActivityAopHelper.getOrCreateContext();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<SupplierFlowImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      SupplierFlowVo vo = new SupplierFlowVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
    context.getIdList().addAll(importedIdList);
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @DataActivity(action = SysDataActivityAction.Export)
  @Override
  public void export(
    Long templateId,
    SupplierFlowSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "enCode",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00195")
      );
      exportOptions.addFieldMappingOption(
        "status",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00134")
      );
      exportOptions.addFieldMappingOption(
        "idField",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00200")
      );
      exportOptions.addFieldMappingOption(
        "titleField",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00200")
      );
      exportOptions.addFieldMappingOption(
        "statusField",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00200")
      );
      exportOptions.addFieldMappingOption(
        "endTimeField",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00200")
      );
      exportOptions.addStringFields(
        "enCode",
        "status",
        "idField",
        "codeField",
        "titleField",
        "statusField",
        "endTimeField",
        "remark"
      );

      String fileName = String.format(
        "供应商流程(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    List<SysDictAllItem> enCodeItems = sysDictService.getDictItems("SCM00195");
    List<SysDictAllItem> statusItems = sysDictService.getDictItems("SCM00134");
    List<SysDictAllItem> idFieldItems = sysDictService.getDictItems("SCM00200");
    List<SysDictAllItem> titleFieldItems = sysDictService.getDictItems(
      "SCM00200"
    );
    List<SysDictAllItem> statusFieldItems = sysDictService.getDictItems(
      "SCM00200"
    );
    List<SysDictAllItem> endTimeFieldItems = sysDictService.getDictItems(
      "SCM00200"
    );
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<SupplierFlowExcelPo> items = new ArrayList<SupplierFlowExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<SupplierFlowItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<SupplierFlowItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (SupplierFlowItemVo item : list) {
        SupplierFlowExcelPo excel = new SupplierFlowExcelPo();
        BeanUtils.copyProperties(item, excel);
        if (item.getEnCode() != null) {
          enCodeItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getEnCode()))
            .findFirst()
            .ifPresent(i -> excel.setEnCode(i.getItemText()));
        }
        if (item.getStatus() != null) {
          statusItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getStatus()))
            .findFirst()
            .ifPresent(i -> excel.setStatus(i.getItemText()));
        }
        if (item.getIdField() != null) {
          final List<String> IdFieldValues = Arrays
            .stream(item.getIdField().split(","))
            .filter(StringUtils::hasText)
            .collect(Collectors.toList());
          excel.setIdField(
            idFieldItems
              .stream()
              .filter(i -> IdFieldValues.contains(i.getItemValue()))
              .map(SysDictAllItem::getItemText)
              .collect(Collectors.joining(","))
          );
        }
        if (item.getTitleField() != null) {
          titleFieldItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getTitleField()))
            .findFirst()
            .ifPresent(i -> excel.setTitleField(i.getItemText()));
        }
        if (item.getStatusField() != null) {
          statusFieldItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getStatusField()))
            .findFirst()
            .ifPresent(i -> excel.setStatusField(i.getItemText()));
        }
        if (item.getEndTimeField() != null) {
          endTimeFieldItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getEndTimeField()))
            .findFirst()
            .ifPresent(i -> excel.setEndTimeField(i.getItemText()));
        }

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "供应商流程(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(SupplierFlowExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过备注查询供应商流程主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByRemark(String remark) {
    return this.baseMapper.getIdByRemark(remark);
  }

  /**
   * 通过备注查询供应商流程多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByRemark(List<String> list) {
    return this.baseMapper.getIdsByRemark(list);
  }

  /**
   * 通过供应商流程主键查询备注
   */
  @Override
  public String getRemarkById(Long id) {
    return this.baseMapper.getRemarkById(id);
  }

  /**
   * 通过供应商流程主键查询备注列表
   */
  @Override
  public List<String> getRemarkByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getRemarkByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("remark"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 供应商流程的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public SupplierFlowVo getVoById(Long id) throws Exception {
    SupplierFlowVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    SupplierFlowNodeSearchParamPo nodeSearchParamPo =
      new SupplierFlowNodeSearchParamPo();
    nodeSearchParamPo.setEnCodeEq(vo.getEnCode());
    nodeSearchParamPo.applySqlSegments();
    nodeSearchParamPo.getExtendData().put("queryMode", "sub");
    nodeSearchParamPo.getExtendData().put("queryParent", "SupplierFlow");
    vo.setNode(supplierFlowNodeService.search(nodeSearchParamPo));

    return vo;
  }

  /**
   * 主列表上要附加“流程节点”子表的部分字段
   * @param items 项目列表
   * @param sort 子表排序
   */
  protected void fillPartOfNode(List<SupplierFlowItemVo> items, String sort) {
    SupplierFlowNodeSearchParamPo nodeSearchParamPo =
      new SupplierFlowNodeSearchParamPo();
    nodeSearchParamPo.setSort(sort);
    nodeSearchParamPo.setSelectFields(
      List.of(
        "enCode",
        "type",
        "nodeUp",
        "node",
        "nodeExceptionStatus",
        "nodeDownExceptionStatus",
        "toUserField",
        "forwardUserField",
        "nodeDoUser",
        "nodeDoRole",
        "nodeSort"
      )
    );
    nodeSearchParamPo.setEnCodeInList(
      items
        .stream()
        .map(SupplierFlowItemVo::getEnCode)
        .collect(Collectors.toList())
    );
    supplierFlowNodeService
      .search(nodeSearchParamPo)
      .forEach(node -> {
        SupplierFlowItemVo item = ListUtils.find(
          items,
          i -> Objects.equals(i.getEnCode(), node.getEnCode())
        );
        if (item == null) return;
        if (item.getNodeType() == null) {
          item.setNodeType(new ArrayList<>());
        }
        item.getNodeType().add(node.getType());

        if (item.getNodeNodeUp() == null) {
          item.setNodeNodeUp(new ArrayList<>());
        }
        item.getNodeNodeUp().add(node.getNodeUp());

        if (item.getNodeNode() == null) {
          item.setNodeNode(new ArrayList<>());
        }
        item.getNodeNode().add(node.getNode());

        if (item.getNodeNodeExceptionStatus() == null) {
          item.setNodeNodeExceptionStatus(new ArrayList<>());
        }
        item.getNodeNodeExceptionStatus().add(node.getNodeExceptionStatus());

        if (item.getNodeNodeDownExceptionStatus() == null) {
          item.setNodeNodeDownExceptionStatus(new ArrayList<>());
        }
        item
          .getNodeNodeDownExceptionStatus()
          .add(node.getNodeDownExceptionStatus());

        if (item.getNodeToUserField() == null) {
          item.setNodeToUserField(new ArrayList<>());
        }
        item.getNodeToUserField().add(node.getToUserField());

        if (item.getNodeForwardUserField() == null) {
          item.setNodeForwardUserField(new ArrayList<>());
        }
        item.getNodeForwardUserField().add(node.getForwardUserField());

        if (item.getNodeNodeDoUser() == null) {
          item.setNodeNodeDoUser(new ArrayList<>());
        }
        item.getNodeNodeDoUser().add(node.getNodeDoUser());

        if (item.getNodeNodeDoUserName() == null) {
          item.setNodeNodeDoUserName(new ArrayList<>());
        }
        item.getNodeNodeDoUserName().add(node.getNodeDoUserName());

        if (item.getNodeNodeDoRole() == null) {
          item.setNodeNodeDoRole(new ArrayList<>());
        }
        item.getNodeNodeDoRole().add(node.getNodeDoRole());

        if (item.getNodeNodeDoRoleRoleName() == null) {
          item.setNodeNodeDoRoleRoleName(new ArrayList<>());
        }
        item.getNodeNodeDoRoleRoleName().add(node.getNodeDoRoleRoleName());

        if (item.getNodeNodeSort() == null) {
          item.setNodeNodeSort(new ArrayList<>());
        }
        item.getNodeNodeSort().add(node.getNodeSort());
      });
  }

  /**
   * 分页查询供应商流程
   * @param search 查询条件
   * @return 供应商流程分页查询结果
   */
  @Override
  public Page<SupplierFlowItemVo> pageSearch(SupplierFlowSearchParamPo search) {
    Page<SupplierFlowItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("en_code asc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(SupplierFlowItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 供应商流程快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'SupplierFlowOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<SupplierFlowItemVo>> searchOptions(
    SupplierFlowSearchParamPo search
  ) {
    search.initSort("en_code asc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询供应商流程
   * @param search 查询条件
   * @return 供应商流程列表查询结果
   */
  @Override
  public List<SupplierFlowItemVo> search(SupplierFlowSearchParamPo search) {
    search.initSort("en_code asc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询供应商流程最后更新时间
   * @param search 查询条件
   * @return 供应商流程最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(SupplierFlowSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }
}
